// 《操作系统概念》 P99
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define BUFFER_SIZE 250
#define READ_END 0
#define WRITE_END 1

char write_msg[BUFFER_SIZE];
char read_msg[BUFFER_SIZE];

int main(int argc, char ** argv) {
    if(argc != 3) {
        fprintf(stderr, "Parameter format error");
        return 1;
    }
    char * src_path = argv[1];
    char * dec_path = argv[2];
    
    FILE * src = fopen(src_path, "r");
    FILE * dec = fopen(dec_path, "w");
    
    fseek(src, 0, SEEK_END);
    int SZ = ftell(src);
    rewind(src);
    fread(write_msg, sizeof(char), SZ, src);
    fclose(src);

    int fd[2];
    pid_t pid;

    if( pipe(fd) == -1 ) {
        fprintf(stderr, "Pipe failed");
        return 1;
    }
    
    pid = fork();
    
    if(pid < 0) {
        fprintf(stderr, "Fork failed");
        return 1;
    }

    if(pid > 0) {
        close(fd[READ_END]);
        write(fd[WRITE_END], write_msg, strlen(write_msg)+1);
        close(fd[WRITE_END]);
    }
    else {
        close(fd[WRITE_END]);
        read(fd[READ_END], read_msg, BUFFER_SIZE);
        printf("read %s\n", read_msg);
        close(fd[READ_END]);

        fwrite(read_msg, sizeof(char), strlen(read_msg), dec);
        fclose(dec);
    }
    return 0;
}
